import { useState, useCallback, useEffect } from "react";
import Taro from "@tarojs/taro";
import { AtTabBar, AtIcon, AtSearchBar } from "taro-ui";
import classnames from "classnames";
import { View, Image, Text } from "@tarojs/components";
import { connect } from "react-redux";
import Loading from "../../components/Loading/Loading";
import { formatCount } from "../../utils/index";
import Music from "../../components/Music/Music";
import { setIsplaying } from "../../redux/actions";
import { getuseInfo, getuseplay, logout } from "../../api/base";
import "./index.scss";

type ListItemInfo = {
  id: number;
  coverImgUrl: string;
  name: string;
  trackCount: number;
  playCount: number;
};

function My(props) {
  const { currentSongInfo, isPlaying, canPlayList, dispatch } = props;
  const [userInfo, setUserInfo] = useState(
    () => Taro.getStorageSync("userInfo") || { profile: "" }
  );
  const [current] = useState<number>(1);
  const [userCreateList, setUserCreateList] = useState<Array<ListItemInfo>>([]);
  const [userCollectList, setUserCollectList] = useState<Array<ListItemInfo>>(
    []
  );
  const [searchValue] = useState<string>("");

  const togglePlay = useCallback(bool => {
    dispatch(setIsplaying(bool));
  }, []);
  const goSearch = useCallback(() => {
    Taro.navigateTo({
      url: `/pages/search/index`
    });
  }, []);
  useEffect(() => {
    if (!Taro.getStorageSync("userInfo")) {
      Taro.reLaunch({
        url: "/pages/login/index"
      });
      return;
    }
    let { userId } = userInfo.profile;
    getuseInfo({ uid: userId }).then(res => {
      setUserInfo(res.data);
    });
    getuseplay({ uid: userId, limit: 300 }).then(res => {
      let creates: Array<ListItemInfo> = [];
      let collects: Array<ListItemInfo> = [];
      res.playlist.forEach(e => {
        if (e.userId == userId) {
          creates.push(e);
        } else {
          collects.push(e);
        }
      });
      setUserCollectList(collects);
      setUserCreateList(creates);
    });
  }, [userInfo]);
  const signOut = useCallback(() => {
    logout();
    Taro.clearStorage();
    Taro.redirectTo({
      url: "/pages/login/index"
    });
  }, []);
  const jumpPage = useCallback(name => {
    Taro.navigateTo({
      url: `/pages/${name}/index`
    });
  }, []);
  const showToast = useCallback(() => {
    Taro.showToast({
      title: "暂未实现，敬请期待",
      icon: "none"
    });
  }, []);
  const switchTab = useCallback(value => {
    if (value !== 0) return;
    Taro.reLaunch({
      url: "/pages/index/index"
    });
  }, []);
  return (
    <View className={classnames("my", { hasMusicBox: !!currentSongInfo.name })}>
      {currentSongInfo.id ? (
        <Music
          songInfo={{
            currentSongInfo,
            isPlaying,
            canPlayList
          }}
          isHome
          onUpdatePlayStatus={togglePlay}
        />
      ) : null}
      <View
        className="l"
        onClick={() => {
          goSearch();
        }}
      >
        <AtSearchBar
          actionName="搜一下"
          disabled
          value={searchValue}
          onChange={() => {
            goSearch();
          }}
        />
      </View>
      <View className="header flex middle">
        <Image
          src={`${userInfo.profile.avatarUrl}?imageView&thumbnail=250x0`}
          className="header-img"
        />
        <View className="cell-main ml20">
          <View className="header-name">{userInfo.profile.nickname}</View>
          <Text className="header-level">LV.{userInfo.level}</Text>
        </View>
        <AtIcon
          prefixClass="fa"
          value="sign-out"
          size="30"
          color="#d43c33"
          className="exit_icon"
          onClick={() => {
            signOut();
          }}
        ></AtIcon>
      </View>
      <View className="flex middle">
        <View className="cell-main tcenter">
          <Text className="">{userInfo.profile.eventCount || 0}</Text>
          <View className="">动态</View>
        </View>
        <View className="cell-main tcenter">
          <Text className="">{userInfo.profile.follows || 0}</Text>
          <View className="">关注</View>
        </View>
        <View className="cell-main tcenter">
          <Text className="">{userInfo.profile.followeds || 0}</Text>
          <View className="">粉丝</View>
        </View>
      </View>
      <View className="flex middle my-item">
        <Image
          className="my-pic"
          src={require("../../assets/images/my/recent_play.png")}
        />
        <View
          className="cell-main"
          onClick={() => {
            jumpPage("recentPlay");
          }}
        >
          最近播放
        </View>
        <Text className="at-icon at-icon-chevron-right"></Text>
      </View>
      <View className="flex middle my-item">
        <Image
          className="my-pic"
          src={require("../../assets/images/my/my_radio.png")}
        />
        <View
          className="cell-main"
          onClick={() => {
            jumpPage("myFans");
          }}
        >
          我的电台
        </View>
        <Text className="at-icon at-icon-chevron-right"></Text>
      </View>
      <View className="flex middle my-item">
        <Image
          className="my-pic"
          src={require("../../assets/images/my/my_collection_icon.png")}
        />
        <View
          className="cell-main"
          onClick={() => {
            showToast();
          }}
        >
          我的收藏
        </View>
        <Text className="at-icon at-icon-chevron-right"></Text>
      </View>
      <View className="my-player">
        <View className="item my-title">
          我创建的歌单 <Text className="desc"> ({userCreateList.length})</Text>{" "}
        </View>
        {userCreateList.length === 0 ? <Loading /> : ""}
        <View className="my-list">
          {userCreateList.map(item => (
            <View className="item flex middle" key={item.id}>
              <Image
                className="play-ico"
                src={`${item.coverImgUrl}?imageView&thumbnail=250x0`}
              />
              <View className="cell-main">
                <View className="l">{item.name}</View>
                <View className="l play-detail">
                  {item.trackCount}首, 播放{formatCount(item.playCount)}次
                </View>
              </View>
            </View>
          ))}
        </View>
      </View>
      <View className="my-player">
        <View className="item my-title">
          我收藏的歌单 <Text className="desc"> ({userCollectList.length})</Text>{" "}
        </View>
        {userCollectList.length === 0 ? <Loading /> : ""}
        <View className="my-list">
          {userCollectList.map(item => (
            <View className="play-item flex middle" key={item.id}>
              <Image
                className="play-ico"
                src={`${item.coverImgUrl}?imageView&thumbnail=250x0`}
              />
              <View className="cell-main">
                <View className="l">{item.name}</View>
                <View className="l play-detail">
                  {item.trackCount}首, 播放{formatCount(item.playCount)}次
                </View>
              </View>
            </View>
          ))}
        </View>
      </View>
      <AtTabBar
        fixed
        selectedColor="#d43c33"
        tabList={[
          { title: "发现", iconPrefixClass: "fa", iconType: "feed" },
          { title: "我的", iconPrefixClass: "fa", iconType: "music" }
        ]}
        onClick={e => {
          switchTab(e);
        }}
        current={current}
      />
    </View>
  );
}
My.config = {
  navigationBarTitleText: "我的"
};
export default connect(
  function mapStateToProps(state) {
    return state;
  },
  function mapDispatchToProps(dispatch) {
    return { dispatch };
  }
)(My);
